package trastienda.dao;

import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import trastienda.excepcion.DAOExcepcion;
import trastienda.modelo.Rol;

@Repository
public class RolDAOImpl implements RolDAO {

	@PersistenceContext
	private EntityManager em;

	public void setEm(EntityManager em) {
		this.em = em;
	}

	@SuppressWarnings(value = "unchecked")
	public Collection<Rol> listarTodos() throws DAOExcepcion {
		Collection<Rol> entities = new ArrayList<Rol>();
		try {
			Query q = em.createNamedQuery("Rol.seleccionarTodos");
			entities = q.getResultList();
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
		return entities;
	}

	@SuppressWarnings("unchecked")
	public Collection<Rol> buscarPorNombre(String nombre) throws DAOExcepcion {
		Query q = em.createQuery("select r from Rol r where upper(r.rolNombre) like :nombre ");

		q.setParameter("nombre", "%" + nombre.toUpperCase() + "%");
		return q.getResultList();
	}

	public void insertar(Rol vo) throws DAOExcepcion {
		try {
			em.persist(vo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new DAOExcepcion(e.getMessage());
		}
	}

	public Rol obtener(String rolNombre) throws DAOExcepcion {
		try {
			return em.find(Rol.class, rolNombre);
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
	}

	public void eliminar(String rolNombre) throws DAOExcepcion {
		try {
			Rol r = em.find(Rol.class, rolNombre);
			em.remove(r);
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}  
	}

	public void actualizar(Rol vo) throws DAOExcepcion {
		try {
			em.merge(vo);
		} catch (Exception e) {
			throw new DAOExcepcion(e.getMessage());
		}
	}
}
